package com.spittr.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.stereotype.Repository;
import org.springframework.test.annotation.Repeat;

/**
 * SpringSecurity启动配置类
 * @author zoe
 * 2017年1月17日
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
	
//	@Autowired
//	private DataSource dataSource;
	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		/**  第一种将用户资料存储在内存中   **/
//		auth.inMemoryAuthentication().withUser("user").password("123456").roles("USER").and().withUser("admin").password("admin").roles("USER","ADMIN");
		
		/**  第二种使用关系型数据库  
		//这3个是安全框架默认的查询，前提是你的表跟它预期的一样，一般情况不会，所以要重写这类查询
		//将默认sql查询替换要遵循查询的基本协议。所有查询都将用户名作为唯一的参数。
		String DEF_USERS_BY_USERNAME_QUERY = "select username,password,enabled "
				+ "from users " + "where username = ?";
		String DEF_AUTHORITIES_BY_USERNAME_QUERY = "select username,authority "
				+ "from authorities " + "where username = ?";
		String DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY = "select g.id, g.group_name, ga.authority "
				+ "from groups g, group_members gm, group_authorities ga "
				+ "where gm.username = ? " + "and g.id = ga.group_id "
				+ "and g.id = gm.group_id";
		
		//查询用户名，密码，是否启用等，用来进行用户认证
		auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery(DEF_USERS_BY_USERNAME_QUERY);
		//查询用户所授予的权限，用来进行鉴权  0或多条
		auth.jdbcAuthentication().dataSource(dataSource).authoritiesByUsernameQuery(DEF_AUTHORITIES_BY_USERNAME_QUERY);
		//查询用户群组的成员所授予的权限 0或多条
		auth.jdbcAuthentication().dataSource(dataSource).groupAuthoritiesByUsername(DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY);
		**/
		
		/**  第三种使用自定义认证，随意搭配方式   **/
		UserDetailsService userDetailsService = new SecurtityUserDetailService();
		auth.userDetailsService(userDetailsService);
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequests = http.authorizeRequests();
		
		/**在authorizeRequests.antMatchers()的返回值中可以继续调用hasAnyAuthority()或者hasRole()这2个方法,
		看起来一个是权限,一个是角色,但是仔细研究,你会发现,hasRole只是hasAnyAuthority它的一个简写版
		所以在这个框架中,我认为能控制到角色这一层**/
		//Specify that URLs require a particular authority.
		authorizeRequests.antMatchers("/form.do").hasAuthority("ROLE_ADMIN");
		//Shortcut for specifying URLs require a particular role. If you do not want to have "ROLE_" automatically inserted see hasAuthority(String).
		authorizeRequests.antMatchers("/form.do").hasRole("ADMIN");
		
		authorizeRequests.antMatchers("/form.do").authenticated();//authenticated()必须已经登录了应用
		authorizeRequests.anyRequest().permitAll();//允许其他请求通过
		http.formLogin().loginPage("/login.html").loginProcessingUrl("/login.do").defaultSuccessUrl("/index.html")//登录首页，默认验证通过后登录index.html，验证请求/login.do
		.and().httpBasic()//开启httpBasic认证
		.and().logout().logoutUrl("/logout.do").logoutSuccessUrl("/login.html")//登出后，跳转login.html
		.and().rememberMe().tokenValiditySeconds(3600).key("securityKey")//记住我 cookies 中会记录 一小时后失效 60*60
		.and().csrf().disable();//禁用CSRF保护功能
	}
}
